package realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;


/**
 * 自定义Realm：实现md5加密认证
 *
 * @author lwh
 */

public class CustomerMd5Realm extends AuthorizingRealm {

    private final Integer MD5_TIMES = 1024;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal = String.valueOf(principals.getPrimaryPrincipal());
        System.out.println("角色信息：" + primaryPrincipal);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 查询数据库，拿到对应的角色
        simpleAuthorizationInfo.addRoles(Arrays.asList("admin","user"));

        simpleAuthorizationInfo.addStringPermissions(Arrays.asList("user:*:01", "product:create:*"));

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String principal = String.valueOf(token.getPrincipal());
        String credential = String.valueOf(token.getCredentials());

        if ("zhangsan".equals(principal)) {
            String salt = "X0*7ps";

            return new SimpleAuthenticationInfo(principal, "e4f9bf3e0c58f045e62c23c533fcf633", ByteSource.Util.bytes(salt), this.getName());
        }

        return null;
    }
}
